<template>
    <div class="container p-5" style="height: calc(100vh - 84px)">
        <!-- 搜索和筛选区 -->

        <div
            class="flex flex-col md:flex-row md:items-center justify-between gap-4"
        >
            <el-input
                v-model="searchQuery"
                placeholder="搜索项目名称、编号..."
                prefix-icon="Search"
                class="max-w-md"
            />

            <div class="flex items-center gap-3">
                <span class="text-sm text-gray-600">排序方式:</span>
                <el-select
                    v-model="sortType"
                    placeholder="请选择"
                    style="width: 200px"
                    @change="handleSortChange"
                >
                    <el-option
                        label="截止时间优先"
                        value="deadline"
                    ></el-option>
                    <el-option label="优先级优先" value="priority"></el-option>
                    <el-option label="项目编号" value="code"></el-option>
                </el-select>
            </div>
        </div>

        <!-- Tab 栏 -->
        <el-tabs v-model="activeTab" class="mb-6" @tab-change="handleTabChange">
            <el-tab-pane label="待办" name="todo">
                <TodoTab
                    :tasks="filteredTodoTasks"
                    @submit-task="handleSubmitTask"
                    @cancel-submit="handleCancelSubmit"
                    @return-task="handleReturnTask"
                    @group-documents="handleGroupDocuments"
                    @view-report="handleViewReport"
                />
            </el-tab-pane>
            <el-tab-pane label="已办" name="done">
                <DoneTab
                    :tasks="filteredDoneTasks"
                    @group-documents="handleGroupDocuments"
                    @view-report="handleViewReport"
                />
            </el-tab-pane>
            <el-tab-pane label="已完成" name="completed">
                <CompletedTab
                    :tasks="filteredCompletedTasks"
                    @group-documents="handleGroupDocuments"
                    @view-report="handleViewReport"
                />
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import TodoTab from "./components/TodoTab.vue";
import DoneTab from "./components/DoneTab.vue";
import CompletedTab from "./components/CompletedTab.vue";
import { useRouter } from "vue-router";

const router = useRouter();
// 状态管理
const activeTab = ref("todo");
const searchQuery = ref("");
const sortType = ref("deadline");

// 原始任务数据
const tasks = ref([
    // 待办任务
    {
        id: 1,
        name: "城东污水处理厂扩建工程",
        code: "XM-2023-0589",
        type: "市政公用设施",
        amount: "¥25,680,000.00",
        status: "待部门审核",
        deadline: "2023-09-10",
        priority: "高",
        progress: 30,
        assignees: 3,
        stage: 2,
        totalStages: 5,
        company: "市水务集团有限公司",
        isUrgent: true,
    },
    {
        id: 2,
        name: "高新区科技园区道路新建工程",
        code: "XM-2023-0612",
        type: "市政基础设施",
        amount: "¥18,450,000.00",
        status: "待公司审核",
        deadline: "2023-09-10",
        priority: "高",
        progress: 60,
        assignees: 2,
        stage: 3,
        totalStages: 5,
        company: "高新区管委会",
        isUrgent: true,
    },
    {
        id: 3,
        name: "城南生态公园景观工程",
        code: "XM-2023-0576",
        type: "园林绿化",
        amount: "¥9,860,000.00",
        status: "待提交",
        deadline: "2023-09-15",
        priority: "高",
        progress: 20,
        assignees: 1,
        stage: 1,
        totalStages: 5,
        company: "市园林局",
        isUrgent: false,
    },
    {
        id: 4,
        name: "幸福家园小区建设工程",
        code: "XM-2023-0591",
        type: "房建工程",
        amount: "¥42,350,000.00",
        status: "部门审核中",
        deadline: "2023-09-20",
        priority: "中",
        progress: 40,
        assignees: 2,
        stage: 2,
        totalStages: 5,
        company: "市住建局",
        isUrgent: false,
    },

    // 已办任务
    {
        id: 5,
        name: "市人民医院门诊楼扩建",
        code: "XM-2023-0567",
        type: "房建工程",
        amount: "¥56,890,000.00",
        status: "公司审核中",
        deadline: "2023-09-25",
        priority: "中",
        progress: 70,
        assignees: 2,
        stage: 4,
        totalStages: 5,
        company: "市卫健委",
        isUrgent: false,
        handled: true,
    },
    {
        id: 6,
        name: "滨河路雨污分流改造工程",
        code: "XM-2023-0582",
        type: "市政基础设施",
        amount: "¥12,560,000.00",
        status: "审核驳回",
        deadline: "2023-09-18",
        priority: "高",
        progress: 30,
        assignees: 1,
        stage: 2,
        totalStages: 5,
        company: "市市政工程处",
        isUrgent: false,
        handled: true,
    },

    // 已完成任务
    {
        id: 7,
        name: "城市展览馆装修工程",
        code: "XM-2023-0543",
        type: "装饰装修",
        amount: "¥8,760,000.00",
        status: "审核通过",
        deadline: "2023-08-30",
        priority: "中",
        progress: 100,
        assignees: 3,
        stage: 5,
        totalStages: 5,
        company: "市文旅局",
        isUrgent: false,
        completed: true,
    },
    {
        id: 8,
        name: "开发区标准化厂房建设",
        code: "XM-2023-0521",
        type: "工业建筑",
        amount: "¥32,450,000.00",
        status: "审核通过",
        deadline: "2023-08-25",
        priority: "高",
        progress: 100,
        assignees: 4,
        stage: 5,
        totalStages: 5,
        company: "开发区管委会",
        isUrgent: false,
        completed: true,
    },
]);

// 筛选和排序逻辑
const filteredTasks = computed(() => {
    let result = [...tasks.value];

    // 搜索筛选
    if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase();
        result = result.filter(
            (task) =>
                task.name.toLowerCase().includes(query) ||
                task.code.toLowerCase().includes(query) ||
                task.company.toLowerCase().includes(query)
        );
    }

    // 排序
    return result.sort((a, b) => {
        switch (sortType.value) {
            case "deadline":
                return new Date(a.deadline) - new Date(b.deadline);
            case "priority":
                const priorityOrder = { 高: 3, 中: 2, 低: 1 };
                return priorityOrder[b.priority] - priorityOrder[a.priority];
            case "code":
                return a.code.localeCompare(b.code);
            default:
                return 0;
        }
    });
});

// 分类任务
const filteredTodoTasks = computed(() =>
    filteredTasks.value.filter((task) => !task.handled && !task.completed)
);

const filteredDoneTasks = computed(() =>
    filteredTasks.value.filter((task) => task.handled && !task.completed)
);

const filteredCompletedTasks = computed(() =>
    filteredTasks.value.filter((task) => task.completed)
);

// 事件处理
const handleTabChange = (tab) => {
    activeTab.value = tab;
};

const handleSortChange = () => {
    // 排序变化时会自动触发计算属性更新
};

const handleSubmitTask = (taskId) => {
    const task = tasks.value.find((t) => t.id === taskId);
    if (task) {
        ElMessageBox.confirm(
            `确定要提交【${task.name}】的审核吗？`,
            "提交确认",
            {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "info",
            }
        )
            .then(() => {
                task.status = "部门审核中";
                ElMessage.success(`【${task.name}】已提交审核`);
            })
            .catch(() => {
                // 取消提交
            });
    }
};

const handleCancelSubmit = (taskId) => {
    const task = tasks.value.find((t) => t.id === taskId);
    if (task) {
        ElMessageBox.confirm(
            `确定要取消【${task.name}】的提交吗？`,
            "取消确认",
            {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }
        )
            .then(() => {
                task.status = "待提交";
                ElMessage.success(`【${task.name}】已取消提交`);
            })
            .catch(() => {
                // 取消操作
            });
    }
};

const handleReturnTask = (taskId) => {
    const task = tasks.value.find((t) => t.id === taskId);
    if (task) {
        ElMessageBox.prompt(`请输入退回【${task.name}】的原因`, "退回原因", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            inputType: "textarea",
        })
            .then(({ value }) => {
                if (task.stage > 1) task.stage--;
                task.status = "审核退回";
                task.handled = true;
                ElMessage.success(`【${task.name}】已退回`);
            })
            .catch(() => {
                // 取消退回
            });
    }
};

const handleGroupDocuments = (taskId) => {
    const task = tasks.value.find((t) => t.id === taskId);
    router.push("/settMgmt/docCompilation");
    if (task) {
        ElMessage.info(`正在为【${task.name}】进行资料组卷`);
        // 实际应用中这里会打开资料组卷弹窗或页面
    }
};

const handleViewReport = (taskId) => {
    const task = tasks.value.find((t) => t.id === taskId);
    router.push("/settMgmt/vrReports");
    if (task) {
        ElMessage.info(`正在查看【${task.name}】的校验报告`);
        // 实际应用中这里会打开校验报告弹窗或页面
    }
};
</script>

<style scoped>
/* 主页面样式补充 */
.el-tabs {
    @apply bg-white rounded-lg shadow-sm p-4;
}

.el-tabs__header {
    @apply mb-6;
}

.el-tabs__item {
    @apply text-gray-700 hover:text-primary;
}

.el-tabs__item.is-active {
    @apply text-primary font-medium;
}
</style>
